const ORDER_KEY = '^orders$'

class Orders {
  constructor() {
    this.list = wx.getStorageSync(ORDER_KEY) || []
  }
  add(data) {
    /**
     * 当购物车有此类食物，只需要姜该食物的count+1
     * 当购物车没有此类食物，直接添加该数据
     */
    // data.count = 1
    const isHave = () => {
      return this.list.findIndex(e => e.id == data.id)
    }
    let hIndex = isHave()
    if (hIndex != -1) {
      this.list.forEach((e, i) => {
        if (i == hIndex) {
          e.count++
        }
      });
    } else {
      data.count = 1
      this.list.push(data)
    }

    this.setOrderList(this.list)
  }
  delete(data) {
    const isHave = () => {
      return {
        index: this.list.findIndex(e => e.id == data.id),
        ditem: this.list.find(e => e.id == data.id)
      }
    }
    let result = isHave()
    if (result.ditem.count > 1) {
      result.ditem.count--
        this.list.splice(result.index, 1, result.ditem)
    } else {
      this.list.splice(result.index, 1)
    }

    this.setOrderList(this.list)
  }

  setOrderList(list) {
    wx.setStorageSync(ORDER_KEY, list)

    // if (list.length > 0) {
    //   wx.setTabBarBadge({
    //     index: 1,
    //     text: String(list.length),
    //   })
    // } else {
    //   wx.removeTabBarBadge({ index: 1 })
    // }
  }

  clear() {
    wx.removeStorageSync(ORDER_KEY)
    // wx.removeTabBarBadge({ index: 1 })
  }

  // get list(){
  //   return wx.getStorageSync(ORDER_KEY) || []
  // }
  // set list(val){
  //   this.list = val
  // }


}

export default Orders